import React from 'react';
import PropTypes from 'prop-types';
import Checkbox from '../Input/Checkbox';

class CheckBox extends React.PureComponent {
    displayName = 'CheckBox';

    static contextTypes = {
        onChangeChecked: PropTypes.func
    }

    constructor (props) {
        super(props);
        if (props.header) {
            props.datum.bindHeader(this.forceUpdate.bind(this));
        } else {
            props.datum.bind(props.id, this.forceUpdate.bind(this));
        }
    }

    componentWillUnmount () {
        if (this.props.header) {
            this.props.datum.unbindHeader();
        } else {
            this.props.datum.unbind(this.props.id);
        }
    }

    handleChange = (v, checked) => {
        const { datum, id, header } = this.props;
        if (header) {
            datum.setHeader(checked ? 1 : 0);
        } else {
            datum.set(id, checked ? 1 : 0);
        }
        if (this.props.onChange) {
            this.props.onChange(datum.getValue(), id);
        }
    }

    checkDisabled () {
        const { datum, id, disabled } = this.props;
        if (disabled) { return true; }
    
        return datum.isDisabled(id);
    }

    render () {
        const { datum, id, className, header } = this.props;
        const checked = header ? datum.getHeaderChecked() : datum.getChecked(id);

        return <Checkbox checked={checked} className={className}
            disabled={this.checkDisabled()}
            onChange={this.handleChange}
        />;
    }
}

export default CheckBox;
